package com.zjl.springbatch.server.impl;

import com.zjl.springbatch.domain.Employee;
import com.zjl.springbatch.mapper.EmployeeMapper;
import com.zjl.springbatch.server.IEmployeeServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Random;

@Service
public class EmployeeServerImpl implements IEmployeeServer {
    private static final Logger LOGGER = LoggerFactory.getLogger(EmployeeServerImpl.class);

    @Resource
    private EmployeeMapper employeeMapper;

    @Value("${job.data.path}")
    private String path;

    @Override
    public void save(Employee employee) {
        employeeMapper.save(employee);
    }

    @Override
    public void dataInit() throws IOException {
        //1.创建输出文件
        File file = new File(path);
        if(file.exists()){
            file.delete();
        }
        file.createNewFile();

        FileOutputStream fileOutputStream = new FileOutputStream(file);


        //2.创建50w条数据
        //  id   \用户名   年龄   性别
        long begin = System.currentTimeMillis();
        Random random = new Random();
        for (int i = 0; i < 500000; i++) {
            StringBuilder sb = new StringBuilder();
            if(i != 0){
                sb.append("\r\n");
            }
            sb.append(i+1).append(",")//id
                    .append(randomName(random,3)).append(',')//名字
                    .append(random.nextInt(100)).append(',')//年龄
                    .append(random.nextBoolean()?'男':'女')//性别
            ;

            fileOutputStream.write(sb.toString().getBytes(StandardCharsets.UTF_8));
        }
        System.out.println("消耗时间：" + (System.currentTimeMillis() - begin));
        fileOutputStream.close();
        fileOutputStream.flush();
        //3.数据输出

    }

    @Override
    public void truncateAll() {
        employeeMapper.truncateAll();
    }

    @Override
    public void truncateTemp() {
        employeeMapper.truncateTemp();
    }

    private static StringBuilder randomName(Random random,int len){
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < len; i++) {
            sb.append((char) (random.nextInt('龥'-'㐁') + '㐁'));
        }
        return sb;
    }
}
